package GUI;

import Attributes.Person;
import Database.DBLoader;
import TableModels.AttributeTableModelCuanti;
import TableModels.AttributesTableModelCuali;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.swing.DefaultCellEditor;
import javax.swing.JComboBox;
import javax.swing.table.TableCellEditor;

public class PreferenceFrame extends javax.swing.JFrame {

    private static MainWindow parent;    
    private DBLoader database;    
    private AttributesTableModelCuali modelo;
    private AttributeTableModelCuanti modelo1;

    public PreferenceFrame(MainWindow parent) {
        this.parent = parent;
        initComponents();
        parent.setConnectionData(tfUser.getText(), tfPw.getText(), tfIp.getText(), tfPort.getText(), tfDb.getText());
        setLocationRelativeTo(parent);
    }

    public void updateTable(DBLoader database) throws SQLException {
        this.database = database;
        modelo = new AttributesTableModelCuali(database, this);
        modelo.load();
        tCalibrar.setModel(modelo);
        modelo1 = new AttributeTableModelCuanti(database, this);
        modelo1.load();
        tCalibrar1.setModel(modelo1);
    }

    public void setErrorMsg(String err){
        errorMsg.setText(err);
    }    
    
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        tpPestanas = new javax.swing.JTabbedPane();
        pConexion = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        tfUser = new javax.swing.JTextField();
        tfPw = new javax.swing.JTextField();
        tfIp = new javax.swing.JTextField();
        tfPort = new javax.swing.JTextField();
        tfDb = new javax.swing.JTextField();
        bGuardarConexion = new javax.swing.JButton();
        pCalibracion = new javax.swing.JPanel();
        bGuardarCalib = new javax.swing.JButton();
        bCancelarCalib = new javax.swing.JButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jScrollPane1 = new javax.swing.JScrollPane();
        tCalibrar = new javax.swing.JTable(){
            public TableCellEditor getCellEditor(int row, int column) {
                Object value = this.getModel().getValueAt(row, column);
                if(value != null) {
                    if(value instanceof JComboBox) {
                        return new DefaultCellEditor((JComboBox)value);
                    }
                    return getDefaultEditor(value.getClass());
                }
                return super.getCellEditor(row, column);
            }

        };
        jScrollPane2 = new javax.swing.JScrollPane();
        tCalibrar1 = new javax.swing.JTable(){
            public TableCellEditor getCellEditor(int row, int column) {
                Object value = this.getModel().getValueAt(row, column);
                if(value != null) {
                    if(value instanceof JComboBox) {
                        return new DefaultCellEditor((JComboBox)value);
                    }
                    return getDefaultEditor(value.getClass());
                }
                return super.getCellEditor(row, column);
            }

        };
        jSeparator1 = new javax.swing.JSeparator();
        errorMsg = new javax.swing.JLabel();

        setTitle("Preferencias");
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                preferencesClosed(evt);
            }
        });

        jLabel1.setText("Username:");

        jLabel2.setText("Database:");

        jLabel3.setText("IP:");

        jLabel4.setText("Password:");

        jLabel5.setText("Port:");

        tfUser.setText("admin");

        tfPw.setText("admin");

        tfIp.setText("localhost");

        tfPort.setText("1527");

        tfDb.setText("Operativa");

        bGuardarConexion.setText("Guardar");
        bGuardarConexion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarConexionActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pConexionLayout = new javax.swing.GroupLayout(pConexion);
        pConexion.setLayout(pConexionLayout);
        pConexionLayout.setHorizontalGroup(
            pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConexionLayout.createSequentialGroup()
                .addGap(100, 100, 100)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel4)
                    .addComponent(jLabel3)
                    .addComponent(jLabel5)
                    .addComponent(jLabel2))
                .addGap(34, 34, 34)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfDb, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfIp, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPw, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, 120, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(89, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pConexionLayout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(bGuardarConexion, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(150, 150, 150))
        );
        pConexionLayout.setVerticalGroup(
            pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pConexionLayout.createSequentialGroup()
                .addGap(28, 28, 28)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfUser, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(tfPw, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(21, 21, 21)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(tfIp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(tfPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(pConexionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(tfDb, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addComponent(bGuardarConexion)
                .addContainerGap(64, Short.MAX_VALUE))
        );

        tpPestanas.addTab("Conexion", pConexion);

        bGuardarCalib.setText("Guardar");
        bGuardarCalib.setEnabled(false);
        bGuardarCalib.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bGuardarCalibActionPerformed(evt);
            }
        });

        bCancelarCalib.setText("Cancelar");
        bCancelarCalib.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bCancelarCalibActionPerformed(evt);
            }
        });

        tCalibrar.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(tCalibrar);

        jTabbedPane1.addTab("Cualitativos", jScrollPane1);

        tCalibrar1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane2.setViewportView(tCalibrar1);

        jTabbedPane1.addTab("Cuantitativos", jScrollPane2);

        errorMsg.setText(" ");

        javax.swing.GroupLayout pCalibracionLayout = new javax.swing.GroupLayout(pCalibracion);
        pCalibracion.setLayout(pCalibracionLayout);
        pCalibracionLayout.setHorizontalGroup(
            pCalibracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pCalibracionLayout.createSequentialGroup()
                .addGroup(pCalibracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pCalibracionLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                    .addGroup(pCalibracionLayout.createSequentialGroup()
                        .addGap(124, 124, 124)
                        .addComponent(bGuardarCalib)
                        .addGap(18, 18, 18)
                        .addComponent(bCancelarCalib)
                        .addGap(0, 97, Short.MAX_VALUE)))
                .addContainerGap())
            .addComponent(jSeparator1)
            .addGroup(pCalibracionLayout.createSequentialGroup()
                .addComponent(errorMsg)
                .addGap(0, 0, Short.MAX_VALUE))
        );
        pCalibracionLayout.setVerticalGroup(
            pCalibracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pCalibracionLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 246, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pCalibracionLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(bCancelarCalib)
                    .addComponent(bGuardarCalib))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 0, 0)
                .addComponent(errorMsg))
        );

        tpPestanas.addTab("Calibracion", pCalibracion);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tpPestanas)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(tpPestanas)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bGuardarConexionActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarConexionActionPerformed
        parent.setConnectionData(tfUser.getText(), tfPw.getText(), tfIp.getText(),tfPort.getText() , tfDb.getText());
        parent.conectar();
        this.hide();
    }//GEN-LAST:event_bGuardarConexionActionPerformed

    public void enableGuardar(){
        bGuardarCalib.setEnabled(true);
    }
    
private void bGuardarCalibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bGuardarCalibActionPerformed
    Hashtable<Integer, Double> changedRowsFactor = modelo1.getChangedRowsFactor();
    Hashtable<Integer, Double> changedRowsUmbral = modelo1.getChangedRowsUmbral();
    Hashtable<Integer, Boolean> changedRowsExcluyente = modelo1.getChangedRowsExcluyente();
    ArrayList<Person> personas = database.getPersons();

    Enumeration<Integer> keysFactor = changedRowsFactor.keys();
    Enumeration<Integer> keysExcluyente = changedRowsExcluyente.keys();
    Enumeration<Integer> keysUmbral = changedRowsUmbral.keys();

    ArrayList<Integer> changedRows = Collections.list(keysFactor);
    changedRows.addAll(Collections.list(keysExcluyente));
    changedRows.addAll(Collections.list(keysUmbral));

    for (Integer i : changedRows) {
        String atributo = (String) modelo1.getValueAt(i, 0);
        String tipo_atributo = (String) modelo1.getValueAt(i, 1);
        Double factor = changedRowsFactor.get(i);
        Boolean excluyente = changedRowsExcluyente.get(i);
        Double umbral = changedRowsUmbral.get(i);

        int flag = 0;
        if (tipo_atributo.equals("REAL")) {
            flag = 1;
        }
        if (umbral == null) {
            umbral = 0d;
        }

        for (Person p : personas) {
            if (factor != null) {
                p.getAttribute(atributo).setFactor(factor);
            }
            p.getAttribute(atributo).setUmbral(umbral, flag);
            
        }

        if (database.isConnected()) {
            try {
                String query = "";
                if (factor != null && excluyente != null) {
                    query = "update APP.ATRIBUTO set FACTOR=" + factor + ", EXCLUYENTE=" + excluyente + ", UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                } else if (factor != null) // excluyente == null
                {
                    query = "update APP.ATRIBUTO set FACTOR=" + factor + " where nombre='" + atributo + "'";
                } else if (excluyente != null) //factor == null
                {
                    query = "update APP.ATRIBUTO set EXCLUYENTE=" + excluyente + ", UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                } else // ambos son null, pero umbral no
                {
                    query = "update APP.ATRIBUTO set UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                }
                database.execute(query);
            } catch (SQLException ex) {
                parent.setMessage(ex.getMessage());
            }
        }
    }

    changedRowsFactor = modelo.getChangedRowsFactor();
    changedRowsUmbral = modelo.getChangedRowsUmbral();
    changedRowsExcluyente = modelo.getChangedRowsExcluyente();


    keysFactor = changedRowsFactor.keys();
    keysExcluyente = changedRowsExcluyente.keys();
    keysUmbral = changedRowsUmbral.keys();

    changedRows = Collections.list(keysFactor);
    changedRows.addAll(Collections.list(keysExcluyente));
    changedRows.addAll(Collections.list(keysUmbral));

    for (Integer i : changedRows) {
        String atributo = (String) modelo.getValueAt(i, 0);
        String tipo_atributo = (String) modelo.getValueAt(i, 1);
        Double factor = changedRowsFactor.get(i);
        Boolean excluyente = changedRowsExcluyente.get(i);
        Double umbral = changedRowsUmbral.get(i);

        int flag = 0;
        if (tipo_atributo.equals("REAL")) {
            flag = 1;
        }
        if (umbral == null) {
            umbral = 0d;
        }

        for (Person p : personas) {
            if (factor != null) {
                p.getAttribute(atributo).setFactor(factor);
            }
            p.getAttribute(atributo).setUmbral(umbral, flag);
            
        }

        if (database.isConnected()) {
            try {
                String query = "";
                if (factor != null && excluyente != null) {
                    query = "update APP.ATRIBUTO set FACTOR=" + factor + ", EXCLUYENTE=" + excluyente + ", UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                } else if (factor != null) // excluyente == null
                {
                    query = "update APP.ATRIBUTO set FACTOR=" + factor + " where nombre='" + atributo + "'";
                } else if (excluyente != null) //factor == null
                {
                    query = "update APP.ATRIBUTO set EXCLUYENTE=" + excluyente + ", UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                } else // ambos son null, pero umbral no
                {
                    query = "update APP.ATRIBUTO set UMBRAL='" + umbral + "' where nombre='" + atributo + "'";
                }
                database.execute(query);
            } catch (SQLException ex) {
                parent.setMessage(ex.getMessage());
            }
        }
    }
    if (modelo != null) {
        try {
            modelo.load();
            modelo1.load();
            tCalibrar.setModel(modelo);
            tCalibrar1.setModel(modelo1);
        } catch (SQLException ex) {
            System.out.println(ex.getMessage());
        }
    }
    this.setVisible(false);
    parent.conectar();
}//GEN-LAST:event_bGuardarCalibActionPerformed



private void bCancelarCalibActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bCancelarCalibActionPerformed
    try {
        if (modelo != null) {
            modelo.load();
        }
    } catch (SQLException ex) {
        parent.setMessage(ex.getMessage());
    }
    this.setVisible(false);
}//GEN-LAST:event_bCancelarCalibActionPerformed

private void preferencesClosed(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_preferencesClosed
    try {
        if (modelo != null) {
            modelo.load();
        }
    } catch (SQLException ex) {
        parent.setMessage(ex.getMessage());
    }
}//GEN-LAST:event_preferencesClosed


    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PreferenceFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PreferenceFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PreferenceFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PreferenceFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PreferenceFrame(parent).setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bCancelarCalib;
    private javax.swing.JButton bGuardarCalib;
    private javax.swing.JButton bGuardarConexion;
    private javax.swing.JLabel errorMsg;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JPanel pCalibracion;
    private javax.swing.JPanel pConexion;
    private javax.swing.JTable tCalibrar;
    private javax.swing.JTable tCalibrar1;
    private javax.swing.JTextField tfDb;
    private javax.swing.JTextField tfIp;
    private javax.swing.JTextField tfPort;
    private javax.swing.JTextField tfPw;
    private javax.swing.JTextField tfUser;
    private javax.swing.JTabbedPane tpPestanas;
    // End of variables declaration//GEN-END:variables
}
